package com.ruoyi.web.controller.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.TzCarIoLog;
import com.ruoyi.system.domain.vo.CarIoLogDTO;
import com.ruoyi.system.mapper.TzCarIoLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public class CarIoLogListener implements ReadListener<CarIoLogDTO> {

    private TzCarIoLogMapper tzCarIoLogMapper;

    public CarIoLogListener(TzCarIoLogMapper tzCarIoLogMapper) {
        this.tzCarIoLogMapper = tzCarIoLogMapper;
    }

    @Override
    public void invoke(CarIoLogDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if(!data.getClo1().contains("车牌")){
            log.info("无效数据忽略！");
            return;
        }
        if(StringUtils.isEmpty(data.getClo3())&& StringUtils.isEmpty(data.getClo4())){
            log.info("车牌信息为空记录无效！");
            return;
        }
        //补充进出场车牌信息
        if(StringUtils.isEmpty(data.getClo3())){
            data.setClo3(data.getClo4());
        }
        if(StringUtils.isEmpty(data.getClo4())){
            data.setClo4(data.getClo3());
        }
        saveData(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成！");
    }

    private void saveData(CarIoLogDTO data) {
        TzCarIoLog tz = new TzCarIoLog();
        tz.setNoType(data.getClo1());
        tz.setCarType(data.getClo2());
        tz.setCarType(data.getClo2());
        tz.setInNo(data.getClo3());
        tz.setOutNo(data.getClo4());
        tz.setStopArea(data.getClo5());
        tz.setVisitStatus(data.getClo6());
        tz.setOutType(data.getClo7());
        tz.setUserInfo(data.getClo8());
        tz.setInChannel(data.getClo9());
        tz.setOutChannel(data.getClo10());
        tz.setInTime(DateUtils.parseDate(data.getClo11()));
        tz.setOutTime(DateUtils.parseDate(data.getClo12()));
        TzCarIoLog select = new TzCarIoLog();
        select.setInNo(tz.getInNo());
        select.setInTime(tz.getInTime());
        List<TzCarIoLog> db = tzCarIoLogMapper.selectTzCarIoLogList(select);
        if(db!=null && db.size()>0){
            log.info("数据重复，取消导入！");
            return;
        }
        long between = tz.getOutTime().getTime() - tz.getInTime().getTime();
        tz.setSingleTime(between/1000);
        tzCarIoLogMapper.insertTzCarIoLog(tz);
    }
}
